import Router from '@koa/router';
import db from '../mysqlHelper.js';
import logger from '../logger.js';
import response from '../response.js';
import moment from 'moment';
import jsonwebtoken from 'jsonwebtoken';

const router = new Router;

let waitCmds = [];

function addWaitCmd(cmd) {

    waitCmds.push(cmd);
    if (waitCmds.length >= 500) {
        //开始计算毫秒级事务执行时间
        // let start = new Date().getTime();
        let dbCmds = waitCmds.splice(0, 500);
        db.transaction(dbCmds);
        //结束计算毫秒级事务执行时间
        // let end = new Date().getTime();
        // console.log('执行一次事务耗时:', end - start, 'ms', '剩余事务数量:', waitCmds.length);
    }
}


router.post(`/service/Api/Submit/Enterprise/BasicInfo`, async (ctx) => {

    let body = ctx.request.body;
    if (body == null) {
        ctx.body = response.fail("参数不允许为空");
        return;
    }
    if (body.enterpriseName == null) {
        ctx.body = response.fail("缺少必填字段 企业名称");
        return;
    }
    if (body.changeType == null) {
        ctx.body = response.fail("缺少必填字段 变更类型");
        return;
    }
    //查义企业是否存在
    let isExist = await db.checkExist('enterprise', { enterpriseName: body.enterpriseName });
    let changeType = body.changeType;
    delete body.changeType;
    if (isExist) {
        if (changeType == 1) {
            ctx.body = response.fail("相同企业已存在");
            return;
        } else {
            //更新企业信息
            let res = await db.update('enterprise', body, { enterpriseName: body.enterpriseName });
            if (res instanceof Error) {
                logger.error(`enterprise create error :` + res.message, `enterprise:${ctx.state.enterprise.name} method:Submit/Enterprise/BasicInfo body: ${JSON.stringify(body)}`);
                ctx.body = response.fail(`enterprise create error :` + res.message);
                return;
            }
            ctx.body = response.success({});
        }
    }
    else {
        if (changeType == 2) {
            ctx.body = response.fail("企业不存在");
            return;
        } else {
            let res = await db.create('enterprise', body);
            if (res instanceof Error) {
                logger.error(`enterprise create error :` + res.message, `enterprise:${ctx.state.enterprise.name} method:Submit/Enterprise/BasicInfo body: ${JSON.stringify(body)}`);
                ctx.body = response.fail(`enterprise create error :` + res.message);
                return;
            }
        }
    }
});

router.post(`/service/Api/BatchSubmit/Bicycle/BasicInfo`, async (ctx) => {
    let body = ctx.request.body;
    if (body == null) {
        ctx.body = response.fail("参数不允许为空");
        return;
    }
    if (body.bicycleBasicList == null) {
        ctx.body = response.fail("缺少必填字段 车辆基本信息列表");
        return;
    }
    let bicycleBasicList = body.bicycleBasicList;
    let sqls = [];
    for (let i = 0; i < bicycleBasicList.length; i++) {
        let bicycleBasic = bicycleBasicList[i];
        bicycleBasic.enterpriseName = ctx.state.enterprise.name;
        //检查车辆是否存在
        let isExist = await db.checkExist('bicycle', { bicycleCode: bicycleBasic.bicycleCode });
        // 如果存在生成更新事务语句
        if (isExist) {
            sqls.push({ sql: `update bicycle set ? where bicycleCode = ?`, param: [bicycleBasic, bicycleBasic.bicycleCode] });
        } else {
            //不存在生成插入事务语句
            sqls.push({ sql: `insert into bicycle set ?`, param: [bicycleBasic] });
        }
    }
    //执行事务
    let res = await db.transaction(sqls);
    if (res instanceof Error) {
        logger.error(`bicycle create error :` + res.message, `enterprise:${ctx.state.enterprise.name} method:BatchSubmit/Bicycle/BasicInfo body: ${JSON.stringify(body)}`);
        ctx.body = response.fail(`bicycle create error :` + res.message);
        return;
    }
    ctx.body = response.success({});
});

router.post(`/service/Api/Submit/Bicycle/BasicInfo`, async (ctx) => {
    let body = ctx.request.body;
    if (body == null) {
        ctx.body = response.fail("参数不允许为空");
        return;
    }
    if (body.bicycleCode == null) {
        ctx.body = response.fail("缺少必填字段 车辆编码");
        return;
    }
    body.enterpriseName = ctx.state.enterprise.name;
    //检查车辆是否存在
    // let isExist = await db.checkExist('bicycle', { bicycleCode: body.bicycleCode });
    // if (isExist) {
    //更新车辆信息
    let res = await db.update('bicycle', body, { bicycleCode: body.bicycleCode });
    if (res instanceof Error) {

        // logger.error(`bicycle create error :` + res.message,`enterprise:${ctx.state.enterprise.name} method:Submit/Bicycle/BasicInfo body: ${JSON.stringify(body)}`);
        // ctx.body = response.fail(`bicycle create error :` + res.message);
        // return;
    }
    if (res.changedRows == 0) {
        let res = await db.create('bicycle', body);
        if (res instanceof Error) {
            logger.error(`bicycle create error :` + res.message);
            ctx.body = response.fail(`bicycle create error :` + res.message);
            return;
        }
    }
    ctx.body = response.success({});
    // } else {
    //     //插入车辆信息
    //     let res = await db.create('bicycle', body);
    //     if (res instanceof Error) {
    //         logger.error(`bicycle create error :` + res.message);
    //         ctx.body = response.fail(`bicycle create error :` + res.message);
    //         return;
    //     }
    //     ctx.body = response.success({});
    // }
});

router.post(`/service/Api/Submit/Bicycle/Position`, async (ctx) => {
    let body = ctx.request.body;
    // logger.info(`enterprise:${ctx.state.enterprise.name} method:Submit/Bicycle/Position body: ${JSON.stringify(body)}`);
    if (body == null) {
        ctx.body = response.fail("参数不允许为空");
        return;
    }
    if (body.bicycleCode == null) {
        ctx.body = response.fail("缺少必填字段 车辆编码");
        return;
    }
    if (body.bicycleLatitude == null) {
        ctx.body = response.fail("缺少必填字段 纬度");
        return;
    }
    if (body.bicycleLongitude == null) {
        ctx.body = response.fail("缺少必填字段 经度");
        return;
    }
    body.lastTime = moment().format('YYYY-MM-DD HH:mm:ss');

    //检查车辆位置是否存在
    let isExist = await db.checkExist('bicyclePos', { bicycleCode: body.bicycleCode });
    if (isExist) {
        //加入到批量更新事务列表
        addWaitCmd({ sql: `update bicyclePos set ? where bicycleCode = ?`, param: [body, body.bicycleCode] });
        // let res = await db.update('bicyclePos', body, { bicycleCode: body.bicycleCode });
        // if (res instanceof Error) {
        //     logger.error(`update bocycle pos  error :` + res.message);
        //     ctx.body = response.fail(`update bocycle pos error :` + res.message);
        //     return;
        // }
        ctx.body = response.success({});
    } else {
        body.enterpriseName = ctx.state.enterprise.name;
        let res = await db.create('bicyclePos', body);
        if (res instanceof Error) {
            logger.error(`insert bicycle post  error :` + res.message);
            ctx.body = response.fail(`insert bicycle post error :` + res.message);
            return;
        }
        ctx.body = response.success({});
    }
});

router.post(`/service/Api/Submit/User/OrdersInfo`, async (ctx) => {
    let body = ctx.request.body;
    //logger.info(`enterprise:${ctx.state.enterprise.name} method:Submit/User/OrdersInfo body: ${JSON.stringify(body)}`);
    if (body == null) {
        ctx.body = response.fail("参数不允许为空");
        return;
    }
    if (body.orderCode == null) {
        ctx.body = response.fail("缺少必填字段 订单编号");
        return;
    }
    if (body.bicycleCode == null) {
        ctx.body = response.fail("缺少必填字段 车辆编码");
        return;
    }
    if (body.orderState == null) {
        ctx.body = response.fail("缺少必填字段 订单状态");
        return;
    }
    if (body.orderTime == null) {
        ctx.body = response.fail("缺少必填字段 订单时间");
        return;
    }
    body.enterpriseName = ctx.state.enterprise.name;
    // let tableName = `orderInfo_${moment().format('YYYYMM')}`;
    let tableName = `orderInfo_${moment().format('YYYYWW')}`;
    let res = await db.create(tableName, body);
    if (res instanceof Error) {
        logger.error(`insert orders error :` + res.message, `enterprise:${ctx.state.enterprise.name} method:Submit/User/OrdersInfo body: ${JSON.stringify(body)}`);
        ctx.body = response.fail(`insert orders error :` + res.message);
        return;
    }
    ctx.body = response.success({});
});

router.post(`/service/Api/Token/Get`, async (ctx) => {
    let body = ctx.request.body;
    if (body == null) {
        ctx.body = response.fail("参数不允许为空");
        return;
    }
    if (body.appKey == null || body.secret == null) {
        ctx.body = response.fail("缺少必填字段 appKey或appSecret");
        return;
    }
    console.log(`url:${ctx.url} body:${JSON.stringify(body)}`);
    let res = await db.findOne('enterprise', { appKey: body.appKey, secret: body.secret });
    if (res == null) {
        ctx.body = response.fail("appKey或appSecret错误");
        return;
    }
    let token = jsonwebtoken.sign({ name: res.enterpriseName }, 'leimong', { expiresIn: '1h' });
    ctx.body = response.success({ accessToken: token, expires: 3600 });
});

router.post(`/service/Api/Submit/electronicfence/addOrUpdate`, async (ctx) => {
    let body = ctx.request.body;
    if (body == null) {
        ctx.body = response.fail("参数不允许为空");
        return;
    }
    if (body.status == null) {
        ctx.body = response.fail("缺少必填字段 电子围栏状态");
        return;
    }
    body.enterprise = ctx.state.enterprise.name;
    body.lastModify = moment().format('YYYY-MM-DD HH:mm:ss');
    if (body.code == null) {
        let res = await db.create('electronicFence', body);
        if (res instanceof Error) {
            logger.error(`create electronicfence error :` + res.message, `enterprise:${ctx.state.enterprise.name} method:Submit/electronicfence/addOrUpdate body: ${JSON.stringify(body)}`);
            ctx.body = response.fail(`create electronicfence error :` + res.message);
            return;
        }
        ctx.body = response.success({ id: res.insertId });
    }
    else {
        // let isExist = await db.checkExist('electronicfence', { code: body.code });
        // if (isExist) {  
        let res = await db.update('electronicFence', body, { code: body.code });
        if (res instanceof Error) {
            logger.error(`update electronicfence error :` + res.message, `enterprise:${ctx.state.enterprise.name} method:Submit/electronicfence/addOrUpdate body: ${JSON.stringify(body)}`);
            ctx.body = response.fail(`update electronicfence error :` + res.message);
            return;
        }
        // } else {
        //    ctx.body = response.fail("电子围栏不存在");
        //     return;
        // }
    }



}
);
router.post(`/service/Api/Submit/electronicfence/delete`, async (ctx) => {
    let body = ctx.request.body;
    if (body == null) {
        ctx.body = response.fail("参数不允许为空");
        return;
    }
    if (body.code == null) {
        ctx.body = response.fail("缺少必填字段 电子围栏编码");
        return;
    }
    let res = await db.deleteRow('electronicFence', { code: body.code });
    if (res instanceof Error) {
        logger.error(`delete electronicfence error :` + res.message, `enterprise:${ctx.state.enterprise.name} method:Submit/electronicfence/delete body: ${JSON.stringify(body)}`);
        ctx.body = response.fail(`delete electronicfence error :` + res.message);
        return;
    }
    ctx.body = response.success({});
}
);
export { router };